package com.gopay.common.metric;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 指标收集器
 * Created by xuHui on 2017/6/28.
 */
public class MetricCollector {

    private static final Logger logger = LoggerFactory.getLogger(MetricCollector.class);

    private long sleepTime;

    private List<MetricSource> metricSources;

    private String transferUrl;

    private boolean execute = true;

    private long delay = 10000;

    ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();

    public void collect(){
        Thread thread = new Thread(){
            @Override
            public void run(){

                if (!execute) {
                    return;
                }

                for(MetricSource metricSource : metricSources){
                    try {
                        metricSource.record(transferUrl);
                    } catch (Exception e){
                        logger.error("指标采集执行异常：{}", e);
                    }
                }
            }
        };

        service.scheduleAtFixedRate(thread, delay, sleepTime, TimeUnit.MILLISECONDS);
    }

    public void destory() {
        service.shutdown();
    }

    public long getSleepTime() {
        return sleepTime;
    }

    public void setSleepTime(long sleepTime) {
        this.sleepTime = sleepTime;
    }

    public List<MetricSource> getMetricSources() {
        return metricSources;
    }

    public void setMetricSources(List<MetricSource> metricSources) {
        this.metricSources = metricSources;
    }

    public String getTransferUrl() {
        return transferUrl;
    }

    public void setTransferUrl(String transferUrl) {
        this.transferUrl = transferUrl;
    }

    public boolean getExecute() {
        return execute;
    }

    public void setExecute(boolean execute) {
        this.execute = execute;
    }
}
